-- Air780EG Lua script using OpenCPU to connect to Baidu Maps API

local http = require("http")
local json = require("cjson")

local apiKey = "YOUR_BAIDU_MAP_API_KEY"
local address = "北京市海淀区中关村大街1号"

-- Encode the address for URL
address = address:gsub(" ", "+")

-- Construct the URL for the GET request
local url = "http://api.map.baidu.com/geocoding/v3/?address=" .. address .. "&output=json&ak=" .. apiKey

-- Function to perform HTTP GET request
function httpGetRequest(url)
    local client = http.createClient()
    local req = client:request("GET", url)

    req:on("response", function(res)
        res:on("data", function(chunk)
            print("Response chunk received: " .. chunk)
            local data = json.decode(chunk)
            if data.status == 400 then
                print("Error: Invalid request parameters")
            elseif data.status == 404 then
                print("Error: Resource not found")
            else
                print("Geocoded location:")
                print("Latitude: " .. data.result.location.lat)
                print("Longitude: " .. data.result.location.lng)
            end
        end)

        res:on("end", function()
            print("Response ended.")
            client:close()
        end)
    end)

    req:on("error", function(err)
        print("Request error: " .. err)
        client:close()
    end)

    req:send()
end

-- Perform the HTTP GET request
httpGetRequest(url)



